/*
 *  Copyright 2007 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.sequence;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.ActionPage;
import com.blandware.atleap.model.core.ContentPage;
import com.blandware.atleap.model.core.Layout;
import com.blandware.atleap.model.core.Localizable;
import com.blandware.atleap.model.core.Page;
import com.blandware.atleap.model.core.Sequence;
import com.blandware.atleap.service.core.LookupManager;
import com.blandware.atleap.service.core.SequenceManager;
import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
import com.blandware.atleap.service.exception.OwnerNotFoundException;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.SequenceForm;
import com.blandware.atleap.webapp.struts.HeritableComponentDefinition;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.tiles.TilesUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

/**
 * <p>Creates new sequence.
 * </p>
 * <p><a href="CreateSequenceAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version : $Revision: 1.4 $ : 2007/12/17 13:38:25 $
 * @struts.action path="/core/sequence/create"
 * name="sequenceForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-sequence-create, core-sequence-override"
 * @struts.action-forward name="inputForward"
 * path=".core.sequence.create"
 * @struts.action-forward name="viewSequence"
 * path="/core/sequence/view.do"
 * redirect="true"
 * @struts.action-forward name="listSequences"
 * path="/core/sequence/list.do"
 * redirect="false"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/sequence/list.do"
 */
public final class CreateSequenceAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		SequenceForm sequenceForm = (SequenceForm) form;
		Long ownerId;
		if ( !GenericValidator.isBlankOrNull(sequenceForm.getOwnerId()) ) {
			ownerId = Long.valueOf(sequenceForm.getOwnerId());
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing owner ID. Returning to index...");
			}
			return mapping.findForward("admin");
		}

		request.getSession().setAttribute(WebappConstants.OWNER_ID_KEY, ownerId);

		if ( !isCancelled(request) ) {
			LookupManager lookupManager = (LookupManager) getBean(Constants.LOOKUP_MANAGER_BEAN);
			Localizable owner = lookupManager.retrieveLocalizable(ownerId);

			if ( owner == null ) {
				ActionMessages errors = new ActionMessages();
				errors.add("ownerNotFound", new ActionMessage("core.sequence.errors.ownerNotFound"));
				saveErrors(request, errors);
				return mapping.findForward("admin");
			}

			String sequenceIdentifier = sequenceForm.getIdentifier();

			if ( owner instanceof ContentPage || (owner instanceof Layout && !request.isUserInRole("core-sequence-create") || (owner instanceof ActionPage && !request.isUserInRole("core-sequence-create"))) ) {
				Set identifiers;
				if ( owner instanceof ContentPage || owner instanceof ActionPage ) {
                    // Overriding sequence
                    if ( !request.isUserInRole("core-sequence-override") ) {
                        response.sendError(HttpServletResponse.SC_FORBIDDEN);
                        return null;
                    }
					identifiers = WebappUtil.getOverridableSequenceIdentifiers(owner, request);

					if ( !identifiers.contains(sequenceIdentifier) ) {
						ActionMessages errors = new ActionMessages();
						errors.add("sequenceIncorrectIdentifier", new ActionMessage("core.sequence.errors.incorrectIdentifier"));
						saveErrors(request, errors);
						saveToken(request);
						return mapping.getInputForward();
					}
				} else {
                    // Overriding sequence
                    boolean canOverride = request.isUserInRole("core-sequence-override");
                    if ( !canOverride ) {
                        response.sendError(HttpServletResponse.SC_FORBIDDEN);
                        return null;
                    }
					Layout ownerLayout = (Layout) owner;
                    identifiers = WebappUtil.getOverridableSequenceIdentifiers(ownerLayout, request);
                    if ( !identifiers.contains(sequenceIdentifier) ) {
						ActionMessages errors = new ActionMessages();
						errors.add("sequenceIncorrectIdentifier", new ActionMessage("core.sequence.errors.incorrectIdentifier"));
						saveErrors(request, errors);
						saveToken(request);
						return mapping.getInputForward();
					}
				}
			} else {
                // (it's AP or Layout and user can create sequences) OR
                // (its not CP, AP or Layout)
                if ( !request.isUserInRole("core-sequence-create") ) {
				    response.sendError(HttpServletResponse.SC_FORBIDDEN);
				    return null;
			    }
            }

			Sequence sequence = new Sequence();
			WebappUtil.copyProperties(sequence, sequenceForm, request);

			SequenceManager sequenceManager = (SequenceManager) getBean(Constants.SEQUENCE_MANAGER_BEAN);

			Long sequenceId;
			try {
				sequenceId = sequenceManager.createSequence(sequence, ownerId);

                // updating cache
                CacheUtil cacheUtil = CacheUtil.getInstance(request);
                if (owner instanceof Layout) {
                    Layout layout = (Layout) owner;
                    String definition = layout.getDefinition();
                    do {
                        cacheUtil.flushLayoutSequenceCache(definition);
                        definition = ((HeritableComponentDefinition) TilesUtil.getDefinition(definition, request, servlet.getServletContext())).getExtends();
                    } while (definition != null);
                } else if (owner instanceof Page) {
                    Page page = (Page) owner;
                    CacheUtil.SequenceData sequenceData = new CacheUtil.SequenceData(sequenceId);
                    cacheUtil.putPageSequenceInCache(sequenceData, page.getUri(), sequence.getIdentifier());
                }
            } catch ( OwnerNotFoundException e ) {
				ActionMessages errors = new ActionMessages();
				errors.add("ownerNotFound", new ActionMessage("core.sequence.errors.ownerNotFound"));
				saveErrors(request, errors);
				return mapping.findForward("admin");
			} catch ( BeanAlreadyExistsException e ) {
				// sequence already exists
				ActionMessages errors = new ActionMessages();
				errors.add("sequenceAlreadyExists", new ActionMessage("core.sequence.errors.alreadyExists"));
				saveErrors(request, errors);
				saveToken(request);
				return mapping.getInputForward();
			}
			request.getSession().setAttribute(WebappConstants.SEQUENCE_ID_KEY, sequenceId);
			return mapping.findForward("viewSequence");
		} else {
			// action was cancelled - return to page with list of sequences
			return mapping.findForward("listSequences");
		}
	}
}